package com.example;

import com.example.utils.ExcelReader;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
public class ExcelController {

    @ModelAttribute("excelData")
    public List<List<List<String>>> getExcelData() {
        return new ArrayList<>();
    }

    @GetMapping("/ClassTable")
    public String index(Model model, @ModelAttribute("excelData") List<List<List<String>>> excelData) {
        model.addAttribute("data", excelData);
        return "ClassTable";
    }

    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file,
                                   RedirectAttributes redirectAttributes,
                                   Model model,
                                   @ModelAttribute("excelData") List<List<List<String>>> excelData) {
        try {
            List<List<List<String>>> newExcelData = ExcelReader.readExcelWithMultipleSheets(file.getInputStream());
            excelData.clear();
            excelData.addAll(newExcelData);
            model.addAttribute("data", excelData);
        } catch (IOException e) {
            redirectAttributes.addFlashAttribute("message", "Error reading the file: " + e.getMessage());
            e.printStackTrace();
            return "/ClassTable";
        }

        return "/ClassTable";
    }
}
